<template>
    <div class="result-container">
        <div class="title">Popular Searches</div>
        <div class="search-list">
            <div class="search-item" v-for="(item, index) in searchApps" :key="index">
                <div class="row">
                    <div class="popular">
                        <span>Popular ·</span>
                        <a :href="appUrls.get(item.name)" data-nuxt-link class="link" v-if="origin" @click="handleClickApp('Search', item)">
                            {{ link(item).split('?')[0] + '?slug=' + item.slug }}
                            <el-icon><CaretBottom /></el-icon>
                        </a>
                    </div>
                    <div class="search-item-name-container">
                        <a :href="appUrls.get(item.name)" data-nuxt-link class="search-item-name" @click="handleClickApp('Search', item)">{{ item.name }}</a>
                        <div class="free-download">- Free Download</div>
                    </div>
                    <div class="description">{{ item.description }}</div>
                </div>
            </div>
        </div>
        <div class="pagination" v-if="totalPages > 1">
            <button @click="handlePageChange(page - 1)" :disabled="page <= 1">
                <el-icon><ArrowLeft /></el-icon>
            </button>
            <span>{{ `${page} / ${totalPages}` }}</span>
            <button @click="handlePageChange(page + 1)" :disabled="page >= totalPages">
                <el-icon><ArrowRight /></el-icon>
            </button>
        </div>
    </div>
  </template>
  
<script setup>
import { ref, computed, watchEffect, onMounted } from 'vue'
import { homeParams } from '~/utils/homeParams'

definePageMeta({
    title: 'Search',
    layout: 'default'
})

const pageInfo = {
    type: 'apps',
    name: 'APP'
}
const route = useRoute()
const router = useRouter()
const searchQuery = computed(() => route.query.name)
const page = computed(() => Number(route.query.page) || 1)
const origin = ref('')
const appUrls = ref(new Map())

// 获取当前URL
const link = (item) => {
    return `${origin.value}/details?type=${pageInfo.type}&slug=${item.slug}`
}

// 存储搜索结果
const data = ref(null)

// 获取搜索列表
const fetchData = async () => {
    const response = await $fetch(`/api/all-apps/${searchQuery.value}`, {
        query: {
            page: page.value
        }
    })
    data.value = response
    
    // 当数据更新时，重新生成 URL
    if (process.client) {
        generateUrls()
    }
}

const getDetailUrl = (item) => {
    const queryParams = {
        type: pageInfo.type,
        slug: item.slug,
        ...homeParams()
    }
    return `/details?${new URLSearchParams(queryParams).toString()}`
}

// 生成所有 URL
const generateUrls = () => {
    appUrls.value.clear()
    if (data.value?.apps) {
        data.value.apps.forEach(app => {
            appUrls.value.set(app.name, getDetailUrl(app))
        })
    }
}

const handleClickApp = (type, item) => {
    logEvent('Click_APP', {
        Subzone: type,
        App: item.name,
    })
}

// 监听搜索参数变化并重新获取数据
watchEffect(() => {
    fetchData()
})

const searchApps = computed(() => {
    const apps = data.value?.apps || []
    return apps.map(app => ({
        ...app,
        description: `${app.name} is a popular app with amazing features. Top ranked under the ${app.category} category, it has ${app.downloads} downloads. Download for free on apkuick now.`
    }))
})

const totalPages = computed(() => data.value?.totalPages || 1)

// 处理分页
const handlePageChange = async (newPage) => {
    await router.push({
        query: {
            ...route.query,
            page: newPage
        }
    })
}

// 在组件挂载后初始化
onMounted(() => {
    origin.value = window.location.origin
    generateUrls()
})
</script>
  
<style scoped lang="scss">
.result-container {
    padding: 1rem 0;
    .title {
        @include title;
    }
    .search-list {
        margin-top: 1rem;
        .search-item {
            padding: 1rem 0;
            border-top: 1px solid #eee;
            .row {
                max-width: 600px;
                .popular {
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                    margin-bottom: 0.5rem;
                    font-size: 0.8rem;
                    span {
                        white-space: nowrap;
                        font-weight: 500;
                    }
                    .link {
                        color: #666;
                        word-break: break-all;
                        overflow: hidden;
                        width: 80vw;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        text-decoration: none;
                    }
                }
                .search-item-name-container {
                    color: #f78b17;
                    .search-item-name {
                        color: #f78b17;
                        font-size: 1.5rem;
                        font-weight: 500;
                        text-decoration: none;
                    }
                    .free-download {
                        font-size: 1.2rem;
                        color: #f78b17;
                    }
                    &:hover {
                        text-decoration: underline;
                    }
                }
                .description {
                    font-size: 0.8rem;
                    color: #666;
                    margin-top: 0.5rem;
                }
            }
        }
    }
}
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1rem;
    margin-top: 2rem;
    
    button {
        border: none;
        padding: 0.3rem .8rem;
        border-radius: 4px;
        background: #f78b17;
        cursor: pointer;
        color: #fff;
        font-size: 1.8rem;
        display: flex;
        align-items: center;
        
        &:hover:not(:disabled) {
            background: #f5f5f5;
        }
        
        &:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }
    }
    
    span {
        color: #000;
        font-size: .8rem;
    }
}
</style>